package com.library.servlet;

import com.library.util.DBUtil;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@WebServlet("/borrowBook")
public class BorrowBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonResponse = new JSONObject();

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "请先登录");
            response.getWriter().write(jsonResponse.toString());
            return;
        }
        int userId = (int) session.getAttribute("userId");
        int bookId;
        try {
            bookId = Integer.parseInt(request.getParameter("bookId"));
        } catch (Exception e) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "参数错误");
            response.getWriter().write(jsonResponse.toString());
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            // 检查图书可借数量
            String checkSql = "SELECT available_copies FROM books WHERE id = ? AND status = 'active'";
            try (PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
                checkStmt.setInt(1, bookId);
                try (ResultSet rs = checkStmt.executeQuery()) {
                    if (!rs.next()) {
                        jsonResponse.put("success", false);
                        jsonResponse.put("message", "图书不存在");
                        response.getWriter().write(jsonResponse.toString());
                        return;
                    }
                    int available = rs.getInt("available_copies");
                    if (available <= 0) {
                        jsonResponse.put("success", false);
                        jsonResponse.put("message", "该图书已无可借数量");
                        response.getWriter().write(jsonResponse.toString());
                        return;
                    }
                }
            }
            // 借阅记录插入
            String insertSql = "INSERT INTO borrow_records (user_id, book_id, due_date) VALUES (?, ?, ?)";
            try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
                insertStmt.setInt(1, userId);
                insertStmt.setInt(2, bookId);
                // 默认借阅 30 天
                LocalDateTime dueDate = LocalDateTime.now().plus(30, ChronoUnit.DAYS);
                insertStmt.setTimestamp(3, Timestamp.valueOf(dueDate));
                insertStmt.executeUpdate();
            }
            // 更新图书可借数量
            String updateSql = "UPDATE books SET available_copies = available_copies - 1 WHERE id = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                updateStmt.setInt(1, bookId);
                updateStmt.executeUpdate();
            }
            jsonResponse.put("success", true);
            jsonResponse.put("message", "借阅成功！");
        } catch (SQLException e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "系统错误，请稍后重试");
        }
        response.getWriter().write(jsonResponse.toString());
    }
} 